package entradasalida;

import java.awt.Point;
import java.awt.image.DataBuffer;
import java.awt.image.Raster;
import java.awt.image.SampleModel;
import java.awt.image.WritableRaster;
import java.util.ArrayList;
import java.util.Set;

import javax.media.jai.PlanarImage;
import javax.media.jai.RasterFactory;
import javax.media.jai.TiledImage;

import Jama.Matrix;
import algoritmos.Matriz;

public class Grafico {
	private PlanarImage pInput;
	
	private TiledImage pOutput;

	private int width, height, numBands;

	private int[] inputData;
	
	private ArrayList<Matrix> entrada;

	public Grafico(PlanarImage pInput) {
		this.pInput = pInput;
		width = pInput.getWidth();
		height = pInput.getHeight();
		numBands = pInput.getSampleModel().getNumBands();
		pOutput = new TiledImage(pInput.getMinX(), pInput.getMinY(), width,
				height, pInput.getMinX(), pInput.getMinY(), pInput
						.getSampleModel(), pInput.getColorModel());
		Raster raster = pInput.getData();
		inputData = new int[width * height * numBands];
		raster.getPixels(0, 0, width, height, inputData);
		entrada = new ArrayList<Matrix>();
		for (int i = 0; i < inputData.length; i += numBands){
			Matriz dato = new Matriz(1,numBands);
			for (int j = 0; j < numBands; j++){
				dato.set(0, j , inputData[i+j]); // Componentes RGB
			}
			entrada.add(dato);
		}
	}

	public TiledImage getFicheroSalida(ArrayList<Matrix> centros, ArrayList<Set<Integer>> pertenencias) {
		SampleModel sampleModel = RasterFactory.createBandedSampleModel(
				DataBuffer.TYPE_INT, width, height, numBands);
		WritableRaster raster = RasterFactory.createWritableRaster(sampleModel,
				new Point(0, 0));
		int[] outputArray = new int[inputData.length];
		for (int i = 0; i < outputArray.length; i += numBands){
			Matriz aClass = (Matriz)buscaCentro(i / 3, centros, pertenencias);
			for (int j = 0; j < numBands; j++){
				outputArray[i + j] = (int)aClass.get(0, j);
			}
		}
		raster.setPixels(0,0,width,height,outputArray);
		pOutput.setData(raster);
		return pOutput;
	}
	
	private Matrix buscaCentro(Integer dato, ArrayList<Matrix> centros, ArrayList<Set<Integer>> pertenencias){
		int numClase = 0;
		for (Set<Integer> conjunto : pertenencias){
			if (conjunto.contains(dato)) break;
			numClase++;
		}
		return centros.get(numClase);
	}

	public PlanarImage getPInput() {
		return pInput;
	}

	public void setPInput(PlanarImage input) {
		pInput = input;
	}

	public ArrayList<Matrix> getEntrada() {
		return entrada;
	}

	public void setEntrada(ArrayList<Matrix> entrada) {
		this.entrada = entrada;
	}

}